package com.guigu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.mapper.*;
import com.guigu.pojo.*;
import com.guigu.service.*;
import com.guigu.service.utils.MyIdAdd;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    MyIdAdd myIdAdd;

    @Autowired
    ShopInfoService shopService;//商品Service

    @Autowired
    OrdersParticularsService ordersParticularsService;// 订单详情Service

    @Autowired
    CartService cartService;//购物车Service

    @Autowired
    UsersService userService;//用户Service

    @Autowired
    CompanyRunningWaterService companyService;//公司账户

    @Autowired
    ReturnShopInfoService returnShopInfoService;//退货商品Service

    @Autowired
    PayInfoMapper payInfoMapper;//出库表
    @Autowired
    PayDetailInfoMapper payDetailInfoMapper;//出库详情表
    @Autowired
    OrdersMapper ordersMapper;//订单表
    @Autowired
    OrdersParticularsMapper ordersParticularsMapper;//订单详情表
    @Autowired
    ProvinceMapper provinceMapper;//省
    @Autowired
    CityMapper cityMapper;//市
    @Autowired
    RegionMapper regionMapper;//区
    @Autowired
    DeliveryAddressMapper   deliveryAddressMapper;
    //查询所有订单
    @Override
    public Page<Orders> commqueryAllOrders(Integer loginUserId, Orders orders, Integer pageno, Integer pagesize) {
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<Orders>();
        //查询商户id为当前登录的用户
        queryWrapper.eq("comm_id", loginUserId);
        queryWrapper.eq("is_delete","0");
        //queryWrapper.ne不等于

        queryWrapper.ne("order_state", "o-1");//待付款
        queryWrapper.ne("order_state", "o-6");//已付款
        queryWrapper.ne("order_state", "o-7");//交易关闭


        //获取页面的数据当作条件去查询数据库
        if (orders != null) {
            if (StringUtils.isNotEmpty(orders.getOrderState())) {
                if(orders.getOrderState().equals("o-4")){
                    queryWrapper.or();
                    queryWrapper.eq("order_state","o-9");//等待退货
                    queryWrapper.or();
                    queryWrapper.eq("order_state","o-4");//全部商品退货
                }else {
                    queryWrapper.eq("order_state", orders.getOrderState());
                }
            }
            if (StringUtils.isNotEmpty(orders.getGoodsState())) {
                queryWrapper.eq("goods_state", orders.getGoodsState());
            }
        }
        Page<Orders> page = this.page(new Page<Orders>(pageno, pagesize), queryWrapper);
        for (Orders o : page.getRecords()) {
            o.setUsers(userService.getById(o.getUId()));
        }
        return page;
    }

    //商户确认收货
    @Override
    public Map editOrders(String pId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        Map map = new HashMap();
        map.put("code", 0);
        map.put("msg", "确认收货失败");

        queryWrapper.eq("p_id", pId);
        Orders b = this.getOne(queryWrapper);
        //检查是否为全部退货订单
        if (b != null) {
            queryWrapper=new QueryWrapper<OrdersParticulars>();
            queryWrapper.eq("p_id",b.getId());
            List<OrdersParticulars> ordersParticularsList=ordersParticularsMapper.selectList(queryWrapper);
            int num=0;
            int count=ordersParticularsList.size();
            for(OrdersParticulars o :ordersParticularsList){
                //检查是否属于待退货订单详情
                if(o.getIsReturn()==1){
                    num++;
                }
            }
            if(num==count){
                //说明是该订单下的所有详情都属于退货订单
                b.setOrderState("o-9");
                b.setGoodsState("g-9");
                b.setHarvestDate(new Date());
                Boolean u = this.updateById(b);
                if (u) {
                    map.put("code", 1);
                    map.put("msg", "收货成功");
                }
            }else {
                b.setGoodsState("g-4");
                b.setOrderState("o-2");
                b.setHarvestDate(new Date());
                Boolean u = this.updateById(b);
                if (u) {
                    map.put("code", 1);
                    map.put("msg", "收货成功");
                }
            }
        }
        return map;
    }

    //用户确认结算添加订单
    @Override
    public Map addOrder(Orders order) {
        Map map = new HashMap();
        map.put("code", 0);
        map.put("msg", "创建订单失败");
        //设置订单的状态
        order.setPId(myIdAdd.idadd("300", true));
        order.setOrderDate(new Date());
        order.setOrderState("o-1");
        order.setGoodsState("g-1");
        order.setIsEvaluate("c-1"); //待评价
        order.setIsSettleAccounts(0); //未结算
        order.setIsDelete(0);
        Double sumPrice = 0.0;
        boolean save = this.save(order);
        if (save) {
            //保存订单详情
            List<OrdersParticulars> list = new ArrayList<OrdersParticulars>();
            List<Integer> cartIds = new ArrayList<Integer>();//存入购物车的id
            for (Cart cart : order.getCarts()) {
                ShopInfo shop = shopService.getById(cart.getGId());
                //批量删除购物车
                cartIds.add(cart.getId());
                //减去上架数量
                shop.setShopUpnum(shop.getShopUpnum()-cart.getQuantity());
                shopService.updateById(shop);
                //批量添加详情表
                OrdersParticulars obj = new OrdersParticulars();
                obj.setPId(order.getId());
                obj.setGId(cart.getGId());
                obj.setIsReturn(0);//未退货
                obj.setIsStorage(0);//未出货
                obj.setBuyQuantity(cart.getQuantity());
                obj.setSumPrice(shop.getShopPrice() * cart.getQuantity());
                sumPrice += obj.getSumPrice();
                list.add(obj);
            }
            //批量添加
            boolean b = ordersParticularsService.saveBatch(list);
            if (b) {
                //删除购物车已购商品
                cartService.removeByIds(cartIds);
                //修改订单保存总价格
                order.setSumPrice(sumPrice);
                boolean b1 = this.updateById(order);
                if (b1) {
                    map.put("code", 1);
                    map.put("msg", "创建订单成功");
                    map.put("oid", order.getId());//将订单id传回页面
                }
            }
        }
        return map;
    }

    @Override
    public Map updateOrders(Integer id) {
        Map map = new HashMap();
        map.put("code", 0);
        map.put("msg", "确认提货失败");
        QueryWrapper<Orders> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id",id);
        Orders o=this.getOne(queryWrapper);
        if(o!=null){
            o.setOrderState("o-3");
            o.setGoodsState("g-5");
            boolean b=this.updateById(o);
            if(b) {
                map.put("code", 1);
                map.put("msg", "确认成功");
            }
        }
        return map;
    }

    //订单流水号
    @Override
    public List<String> getIds(String str) {
        List<String> list = new ArrayList<String>();
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<Orders>();
        queryWrapper.likeRight("p_id", str);
        List<Orders> tempList = this.list(queryWrapper);
        for (Orders obj : tempList) {
            list.add(obj.getPId());
        }
        return list;
    }

    //根据订单id查询订单信息
    @Override
    public Orders queryOrderById(Integer id) {
        QueryWrapper<Orders> queryWrapper=new QueryWrapper();
        queryWrapper.eq("is_delete","0");
        queryWrapper.eq("id",id);
        Orders order = this.getOne(queryWrapper);
        order.setCommUser(userService.getById(order.getCommId()));
        order.setOrdersDetails(ordersParticularsService.queryDetailByOid(order.getId()));
        //查询地址
        DeliveryAddress addr = deliveryAddressMapper.selectById(order.getCommUser().getAdId());
        addr.setProvinceName(provinceMapper.selectById(addr.getPId()).getName());
        addr.setCityName(cityMapper.selectById(addr.getCId()).getName());
        addr.setRegion(regionMapper.selectById(addr.getRId()).getName());
        order.getCommUser().setDeliveryAddressPick(addr);
        return order;
    }

    //用户订单查询
    @Override
    public Page<Orders> queryAllOrders(Orders orders, Integer pageno, Integer pagesize) {
        QueryWrapper<Orders> queryWrapper =
                new QueryWrapper<Orders>();
        queryWrapper.eq("is_delete",0);
        queryWrapper.select().orderByDesc("order_date");
        //用户id
        if (orders.getUId() != null) {
            queryWrapper.eq("u_id", orders.getUId());
        }
        //自增id
        if (orders.getId() != null) {
            queryWrapper.eq("id", orders.getId());
        }
        //订单流水号
        if (StringUtils.isNotBlank(orders.getPId())) {
            queryWrapper.eq("p_id", orders.getPId());
        }
        //订单状态
        if (StringUtils.isNotBlank(orders.getOrderState())) {
            queryWrapper.eq("order_state", orders.getOrderState());
        }
        //货物状态
        if (StringUtils.isNotBlank(orders.getOrderState())) {
            queryWrapper.eq("order_state", orders.getOrderState());
        }

        //是否评价
        if(StringUtils.isNotBlank(orders.getIsEvaluate())){
            queryWrapper.eq("is_evaluate", orders.getIsEvaluate());
        }
        //是否评价
        if(orders.getIsDelete()!=null){
            queryWrapper.eq("is_delete", orders.getIsDelete());
        }
        Page<Orders> page = this.page(new Page<Orders>(pageno, pagesize), queryWrapper);
        for (Orders o : page.getRecords()) {
            o.setCommUser(userService.getById(o.getCommId()));
            o.setOrdersDetails(ordersParticularsService.queryDetailByOid(o.getId()));
        }
        return page;
    }

    //用户操作订单
    @Override
    @Transactional
    public Map payOrder(Orders order) {
        Map map = new HashMap();
        map.put("code", 0);
        map.put("msg", "操作失败");
        if (StringUtils.isNotBlank(order.getOrderState())) {
            Orders order2 = this.getById(order.getId());
            Users user = userService.getById(order2.getUId());
            //支付
            if (order.getOrderState().equals("o-6")) {
                if (user.getBalance() > order2.getSumPrice()) {
                    Users user2 = new Users();
                    //用户减去金额
                    user2.setId(user.getId());
                    user2.setBalance(user.getBalance() - order2.getSumPrice());
                    boolean b1 = userService.updateById(user2);
                    //存入公司账户
                    Users account = userService.getById(10);
                    account.setBalance(account.getBalance()+ order2.getSumPrice());
                    boolean b2 = userService.updateById(account);
                    //添加订单流水
                    CompanyRunningWater water=new CompanyRunningWater();
                    water.setPipelineId(myIdAdd.idadd("500",true));
                    water.setAccountId(user2.getId());//付款人
                    water.setUid(account.getId()); //收钱人
                    water.setOid(order.getPId()); //订单编号
                    water.setRmoney(order2.getSumPrice()); //金额
                    water.setRdate(new Date());
                    water.setRtype(1);
                    water.setIsDelete(0);
                    boolean b3=companyService.save(water);
                    //修改订单为已付款
                    order.setPaymentDate(new Date());
                    boolean b4=this.updateById(order);
                    if (b1 && b2 && b3 && b4){
                        map.put("code", 1);
                        map.put("msg", "付款成功!");
                    }else {
                        throw new RuntimeException();
                    }

                } else {
                    map.put("msg", "付款失败!用户余额不足!请充值!");
                }
            }
            //取消订单
            else if (order.getOrderState().equals("o-7")) {
                order.setClinchDate(new Date());
                boolean b = this.updateById(order);
                if (b){
                    map.put("code",1);
                    map.put("msg","成功取消订单!");
                }
            }
            //确认收货
            else if (order.getOrderState().equals("o-5")) {
                order.setClinchDate(new Date());
                order.setGoodsState("g-6");
                boolean b = this.updateById(order);
                if (b){
                    map.put("code",1);
                    map.put("msg","收货成功!");
                }
            }
        }
        return map;
    }

    //用户删除订单
    @Override
    public Map delOrder(Orders order) {
        Map map = new HashMap();
        map.put("code", 0);
        map.put("msg", "删除失败");
        order.setIsDelete(1);
        boolean b = this.updateById(order);
        if (b){
            map.put("code", 1);
            map.put("msg", "删除成功");
        }
        return map;
    }

    //商户退货订单
    @Override
    public com.guigu.service.utils.Page queryAllOrdersReturn(Integer loginUserId, Orders orders, Integer pageno, Integer pagesize) {
        List<Orders> list=new ArrayList<>();
//        QueryWrapper<Orders> queryWrapper = new QueryWrapper<Orders>();
//        queryWrapper.eq("comm_id",loginUserId);
//        queryWrapper.eq("goods_state","g-4");
//        queryWrapper.eq("order_state","o-2");
//        queryWrapper.or();
//        queryWrapper.eq("order_state","o-9");
//        queryWrapper.eq("is_delete","0");
        Orders temo_obj=new Orders();
        temo_obj.setCommId(loginUserId);
        List<Orders> ordersList=ordersMapper.queryAllOrdersReturntest(temo_obj);
        //循环查询到的分页数据
        for (Orders o : ordersList){
            boolean x=false;
            o.setUsers(userService.getById(o.getUId()));
            o.setOrdersDetails(ordersParticularsService.queryParticulars(o.getId()));
            if(o.getOrdersDetails().size()>0) {
                List<OrdersParticulars> tempList=new ArrayList();
                for (OrdersParticulars p : o.getOrdersDetails()) {
                    //调用商品里面的根据id查询商品图片
                    p.setShopInfo(shopService.queryShopById(p.getGId()));
                    p.setReturnShopInfo(returnShopInfoService.queryBYid(p.getId()));
                    //检查该订单详情数据，是否属于待退货订单
                    if (p.getIsReturn() == 1 ) {
                        //属于退货订单，检查货物状态是否为【等待用户将货物送到商户，商户等待确认】
                        // 或者【用户拒绝收货，总店已发货，商户等待接收】
                        if(p.getReturnShopInfo()!=null){
                            if(p.getReturnShopInfo().getGoodsState()==1 || p.getReturnShopInfo().getGoodsState()==5 || p.getReturnShopInfo().getGoodsState()==9){
                                tempList.add(p);
                                x = true;
                            }
                        }
                    }
                }
                o.setOrdersDetails(tempList);
            }
            if(x){
                list.add(o);
            }
        }
        com.guigu.service.utils.Page page=new com.guigu.service.utils.Page();
        return page.pageList(list,pageno,pagesize);
    }

    //出库
    @Override
    public com.guigu.service.utils.Page outboundOrder(Orders orders,Integer pageno, Integer pagesize) {
        List<Orders> result=new ArrayList<>();
        //查询所有订单、未被删除、订单状态为已付款、商户id
        QueryWrapper queryWrapper=new QueryWrapper<Orders>();
        queryWrapper.eq("is_delete","0");
        queryWrapper.eq("order_state","o-6");
        if(orders.getCommId()!=null){
            queryWrapper.eq("comm_id",orders.getCommId());
        }
        List<Orders> ordersList=ordersMapper.selectList(queryWrapper);
        //循环订单，检查订单详情是否存在有退货情况
        for(Orders o : ordersList){
            //用于计算订单下的退货详情数量
            int count=0;
            List<OrdersParticulars> resultParticulars=new ArrayList<>();
            //获取详情，并且循环
            queryWrapper=new QueryWrapper<OrdersParticulars>();
            queryWrapper.eq("p_id",o.getId());
            List<OrdersParticulars> ordersParticularsList=ordersParticularsMapper.selectList(queryWrapper);
            Boolean x=false;
            for(OrdersParticulars op : ordersParticularsList){
                //检查详情的出库状态是否不等于未出库，如果属于等于未出库，说明本条订单处于申请中或者已出库，过滤本条数据
                if(op.getIsStorage()!=0){
                    //跳出循环
                    x=true;
                    break;
                }
                //检查是否未退货
                if(op.getIsReturn()==0){
                    //未退货，将详情存入集合内，用于数据展示
                    resultParticulars.add(op);
                }else {
                    //是退货，进行计数
                    count++;
                }
            }
            //检查本条订单是否为出库申请中或已出库
            if(!x){
                //检查退货数量是否小于订单详情数量
                if(count<ordersParticularsList.size()){
                    //退货数量小于订单详情数量，说明没有对全部详情进行退货，那么剩余的详情是需要出库的。
                    o.setOrdersDetails(resultParticulars);
                    result.add(o);
                }
            }
        }
        //进行分页
        return new com.guigu.service.utils.Page().pageList(result,pageno,pagesize);
    }

}
